from flask import render_template, request, jsonify, session, g, abort
from sqlalchemy import or_

from app2 import db
from app2.utils.common.common import login_user_data2, get_webservertime, vip_get_webservertime, vip_default_time
from . import index_blue
from app2.models.models import News, Comment, User, Goods, Order


@index_blue.route("/")
@index_blue.route("/index")
@login_user_data2
def index():
    """首页"""
    # print(request.is_xhr)
    # 查询前6个数据
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)
    # ranks_news = News.query.order_by(News.clicks.desc()).limit(6)

    # nick_name = session.get("nick_name")
    # user_id = session.get("user_id")
    user = g.user
    # user = db.session.query(User).filter(User.id == user_id).first()
    # 获取当前网络时间
    net_time = get_webservertime()
    # 判断当前用户今天是否已经签到
    if user:
        if net_time == user.sign_in:
            user.sing = 1
        else:
            user.sing = 0
        if vip_get_webservertime() > user.vip_create_time:
            # print('进来了')
            user.vip_create_time = vip_default_time()
            user.vip = 0
            db.session.commit()

    # if not user.vip_create_time:
    #     print('-'*50)

    return render_template("index/index.html", user=user, ranks_news=ranks_news)
    # return render_template("index/index.html")


@index_blue.route("/newslist")
def newslist():
    """顶部标题分类新闻切换"""
    # print("进来了")
    # 通过前端的$.get() -- >ajax 向后端提交的参数
    # -->> get 参数存在于url中， 用request.args 获取
    page = request.args.get('page', 1)  # 当前页
    cid = request.args.get('cid', 1)  # 新闻分类   # 若没有cid为None, 则说明用户正在进行搜索操作，定义一个新的分类8
    per_page = request.args.get('per_page', 10)  # 每页显示个数
    # search = request.args.get('search')  # 若进行搜索
    # print(page, cid, per_page)

    page = int(page) if page and page.isdigit() else 1
    cid = int(cid) if cid and cid.isdigit() else 1
    per_page = int(per_page) if per_page and per_page.isdigit() else 10

    # 进行数据库paginate分页查询
    if cid == 1:
        paginate = News.query.order_by(News.create_time.desc()).paginate(page, per_page, False)
    else:
        paginate = db.session.query(News).filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(
            page, per_page, False)
    # paginate = db.session.query(News).order_by(News.id.desc()).paginate(page, per_page, False)
    # 分页查询出来的对象所组成的列表
    new_list = paginate.items

    ret = {
        "totalPage": paginate.pages,
        "newsList": [news.to_dict() for news in new_list],
        "cid": cid
    }

    return jsonify(ret)


@index_blue.route("/detail/<int:news_id>")
@login_user_data2
def detail(news_id):
    """资讯详情"""

    # 获取相应文章
    news = db.session.query(News).filter(News.id == news_id).first()
    if not news:
        abort(404)



    # 若有该文章，进行跳转并让阅读量加1
    if news:
        news.clicks += 1
        db.session.commit()

    # 显示登录状态、显示当前新闻作者是否已被自己关注(后面修改未登陆状态下若点关注应提示登录)
    # nick_name = session.get("nick_name")
    # user_id = session.get("user_id")
    user = g.user
    # 查询该文章的所有评论
    comment_list = [x.to_basic_dict() for x in news.comments.order_by(Comment.create_time.desc())]

    # 右侧热点文章排行
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)


    # print(user, "-"*30)
    if not user:  # 为什么要加这个判断，因为若无登录，则在下面的判断中user.id会报错（None.id会报错）, 在html（jinjia2模板）中， None.id不会报错
        #     # 无登录 显示可以关注
        #     news_autho.can_follow = True
        #     # 显示可以点赞
        news.can_collect = True
        # 未登陆,对评论都显示未点赞
        like_comments = list()
        return render_template("index/detail.html",
                               news=news,
                               comment_list=comment_list,
                               like_comments=like_comments,
                               ranks_news=ranks_news,
                               user=user
                               # news_author=news_author)
                               )
    # # 列表推导式让原本的query对象自动生成查询结果[作者粉丝组成的列表]  None 无 属性 会报错
    # # 判断关注
    # if user.id in [follower.id for follower in followers]:  # 判断登录用户是否在新闻作者的粉丝列表
    #     # (若无登录，session.get("user_id")为None, 执行else, 显示可以关注)
    #     news_author.can_follow = False
    # else:
    #     news_author.can_follow = True

    if vip_get_webservertime() > user.vip_create_time:
        # print('进来了')
        user.vip_create_time = vip_default_time()
        user.vip = 0
        db.session.commit()
    # 判断点赞的文章
    if user.id in [x.id for x in news.collection_user]:
        news.can_collect = False
    else:
        news.can_collect = True

    # # 判断点赞的评论
    like_comments = [x.to_basic_dict() for x in user.like_comments]

    # 获取当前网络时间
    net_time = get_webservertime()
    if net_time == user.sign_in:
        user.sing = 1
    else:
        user.sing = 0

    return render_template("index/detail.html",
                           news=news,
                           comment_list=comment_list,
                           like_comments=like_comments,
                           ranks_news=ranks_news,
                           user=user
                           # news_author=news_author)
                           )


@index_blue.route("/search")
@login_user_data2
def search():
    """进行搜索"""
    search = request.args.get("search")
    # print(search)
    # if not search:
    #     return render_template('index/search.html')
    user = g.user
    page = request.args.get('page')
    page = int(page) if page and page.isdigit() else 1  # 页码不存在或不为纯数字都转为第一页
    paginate = db.session.query(News).filter(
        or_(News.title.like("%" + search + "%"), News.digest.like("%" + search + "%"))).order_by(
        News.create_time.desc()).paginate(page, 1, False)
    news_list = [x.to_dict() for x in paginate.items]


    # 右侧热点文章排行
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)
    # 获取当前网络时间判断用户是否已签到
    net_time = get_webservertime()
    if user:
        if net_time == user.sign_in:
            user.sing = 1
        else:
            user.sing = 0
    return render_template('index/search.html', news_list=news_list, search=search, paginate=paginate, ranks_news=ranks_news, user=user)

# @index_blue.route("/cc")
# def cc():
#     return render_template("index/cc.html")


@index_blue.route("/shop")
@login_user_data2
def shop():
    # 积分商城首页
    user = g.user
    # 右侧热点文章排行
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)
    # 获取当前网络时间
    net_time = get_webservertime()
    # 判断当前用户今天是否已经签到
    if user:
        if net_time == user.sign_in:
            user.sing = 1
        else:
            user.sing = 0
        if vip_get_webservertime() > user.vip_create_time:
            # print('进来了')
            user.vip_create_time = vip_default_time()
            user.vip = 0
            db.session.commit()

    # 获取所有商品
    goods = db.session.query(Goods).all()

    return render_template("index/shop.html", user=user, ranks_news=ranks_news, goods=goods)


@index_blue.route("/shop_detail")
@login_user_data2
def shop_detail():
    """积分商城商品详情页"""
    user = g.user
    # 右侧热点文章排行
    ranks_news = db.session.query(News).order_by(News.clicks.desc()).limit(5)
    # 获取当前网络时间
    net_time = get_webservertime()
    # 判断当前用户今天是否已经签到
    if user:
        if net_time == user.sign_in:
            user.sing = 1
        else:
            user.sing = 0


    # 获取商品的详情
    good_id = request.args.get('good_id')
    # print(good_id)
    good = db.session.query(Goods).filter(Goods.id == good_id).first()
    if not good:
        abort(404)

    return render_template('index/shop_detail.html', good=good, user=user, ranks_news=ranks_news)


@index_blue.route("/good_bug", methods=["POST"])
@login_user_data2
def good_bug():
    """购买商品"""
    # print('进来了')
    # 若用户未登陆则提示登录再购买
    user = g.user
    if not user:
        ret = {
            "errno": 3001,
            "errmsg": "请登录后再进行操作！"
        }
        return jsonify(ret)

    # 获取当前商品的id
    good_id = request.form.get('good_id')

    # 从数据库中查询出该商品
    good = db.session.query(Goods).filter(Goods.id==good_id).first()
    # print('当前该商品', good)

    # 获取当前商品剩余件数
    if good.on_off <= 0:  # 若当前无存货
        ret = {
            "errno": 3002,
            "errmsg": "该商品暂无存货！"
        }
        return jsonify(ret)

    # 判断当前用户积分是否足以购买当前商品
    if user.integral < good.integral:
        ret = {
            "errno": 3003,
            "errmsg": "积分不足！"
        }
        return jsonify(ret)

    # 若购买成功，让当前商品份数减一，用户积分减去相应部分，并让前台重刷新，并记录下该订单
    good.on_off -= 1
    try:
        user.integral -= good.integral
        order = Order(user_id=user.id, good_id=good.id)
        db.session.add(order)
        db.session.commit()
    except Exception as e:
        print(e)
        print('-'*89)

    ret = {
        "errno": 0,
        "errmsg": "购买成功，请联系客服核实订单！"
    }
    return jsonify(ret)





